package com.example.obs.config;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.example.obs.dao.DepartmentMapper;
import com.example.obs.model.domin.Department;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author Kevin
 * @date 2020-09-28 14:34
 */
@Component
public class UserDepartmentConverter implements Converter<Integer>, ApplicationContextAware {

    private static DepartmentMapper departmentMapper;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DepartmentMapper departmentMapper = applicationContext.getBean(DepartmentMapper.class);
        UserDepartmentConverter.departmentMapper = departmentMapper;
    }

    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String value = cellData.getStringValue();
        Department department = departmentMapper.selectDepartmentByName(value);
        if (department != null) {
            return department.getId();
        }
        return 0;
    }

    @Override
    public CellData convertToExcelData(Integer s, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData(s);
    }

}
